<?php
/**
 * 角色控制器
 * User: ws
 * Date: 2018/8/4
 * Time: 21:04
 */

namespace app\admin\controller;

use app\admin\model\AdminMenu as MenuModel;
use app\admin\model\AdminRole as RoleModel;
use app\admin\model\AdminUser as UserModel;

class Role  extends Init
{
    function index(){
        if ($this->request->isAjax()) {
            $list = RoleModel::where('admin_role_id > 1')->paginate(input('limit'))->toArray();
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);die;
        }
        return $this->fetch('list');
    }


    function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            unset($data['admin_role_id']);
            if (RoleModel::create($data)) {
                return json(array('code'=>200,'msg'=>'添加成功'));
            }
            return json(array('code'=>0,'msg'=>'添加失败'));
        }
        $this->assign('menu_list', MenuModel::getAllChild());
        return $this->fetch('add');
    }



    function edit(){
        if ($this->request->isPost()) {
            unset($_GET['admin_role_id']);
            $data = $this->request->post();
            if(empty($data)){
                return json(array('code'=>0,'msg'=>'修改失败'));
            }

            if (RoleModel::update($data)) {
                return json(array('code'=>200,'msg'=>'修改成功'));
            }
            return json(array('code'=>0,'msg'=>'修改失败'));
        }

        $row = RoleModel::where('admin_role_id', input('id'))->find()->toArray();
        $row['role_auth'] = json_decode($row['role_auth']);
        $this->assign('data_info', $row);
        $this->assign('menu_list', MenuModel::getAllChild());
        return $this->fetch('add');
    }


    function del(){
        // 判断是否有用户绑定此角色
        if (UserModel::where('admin_role_id', input('admin_role_id'))->find()) {
            return json(array('code'=>0,'msg'=>'删除失败，有绑定账号'));
        }
        $result = RoleModel::destroy(input('admin_role_id'));
        if($result){
            return json(array('code'=>200,'msg'=>'删除成功'));
        }else{
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
    }

}